package com.mybatisflex.admin.interceptor;

import com.alibaba.fastjson.JSON;
import com.mybatisflex.admin.entity.AccountSession;
import com.mybatisflex.admin.mapper.AccountSessionMapper;
import com.mybatisflex.admin.util.JwtUtil;
import com.mybatisflex.admin.util.ResponseUtil;
import com.mybatisflex.admin.util.Result;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigInteger;
import java.util.Map;

import static com.mybatisflex.admin.entity.table.AccountSessionTableDef.ACCOUNT_SESSION;


@Component
public class LoginInterceptor implements HandlerInterceptor {

    public static final String loginAccountId = "loginAccountId";
    public static final String loginSessionId = "sessionId";

    @Resource
    private AccountSessionMapper sessionMapper;


    public static BigInteger getLoginAccountId(){
        return (BigInteger) RequestContextHolder.getRequestAttributes()
                .getAttribute(loginAccountId, RequestAttributes.SCOPE_REQUEST);
    }


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");

        if (!StringUtils.hasText(token)) {
            renderNotLogin(response);
            return false;
        }

        Map<String, Object> map = JwtUtil.parseToken(token);
        Object sessionId = map.get(loginSessionId);
        if (sessionId == null){
            renderNotLogin(response);
            return false;
        }

        AccountSession accountSession = sessionMapper.selectOneByCondition(ACCOUNT_SESSION.ID.eq(sessionId));
        if (accountSession == null){
            renderNotLogin(response);
            return false;
        }

        request.setAttribute(loginAccountId, accountSession.getAccountId());
        return true;
    }


    private static void renderNotLogin(HttpServletResponse response){
        String json = JSON.toJSONString(Result.error(99, "当前用户未登录"));
        ResponseUtil.response(response, json);
    }

}
